﻿if (typeof Axis == "undefined") Axis = {};
if (typeof Axis.Admin == "undefined") Axis.Admin = {};
var checkListAuthorized;
var first = true;
Axis.Admin.MemberGift = {
    Init: function () {
        var thisObj = this;
        thisObj.Event();
        thisObj.Grid.Init();
        var cmaskdate = new CMaskDate();
        cmaskdate.Init($("input[role=datepicker]"));
        $("#imgUserExport").bind('click', function () {
            ExportExcel(0, 0);
        });
    },

    Grid: {
        ID: "#GridContents",
        PagesID: "#GridPages",
        GridURL: "Service/UserService.ashx?Action=GET&Context=GroupUser",
        Instance: null,
        Init: function () {
            var thisObj = this;
            var options = {
                datatype: function () {
                    if (first == true) {
                        first = false;
                        return;
                    }
                    //  var pData = { ProjectID: $("#ddlProjectList").val(), GiftID: $("#ddlGift").val(), GiftReveiced: $("#ddlStatus").val() };
                    //  var pData = { ProjectID: $("#ddlProjectList").val(), GiftID: 18, GiftReveiced: $("#ddlStatus").val(), FromDate: $("#txtFromDate").val(), ToDate: $("#txtToDate").val(), FromMark: $("#txtFromMark").val(), ToMark: $("#txtToMark").val() };

                    var pData = { ProjectID: $("#ddlProjectList").val(), GiftID: $("#ddlGift").val(), GiftReveiced: $("#ddlStatus").val(), FromDate: $("#txtFromDate").val(), ToDate: $("#txtToDate").val(), FromMark: $("#txtFromMark").val(), ToMark: $("#txtToMark").val() };
                    //var pData = { ProjectID: $("#ddlProjectList").val(), GiftID: 26, GiftReveiced: $("#ddlStatus").val(), FromDate: $("#txtFromDate").val(), ToDate: $("#txtToDate").val(), FromMark: $("#txtFromMark").val(), ToMark: $("#txtToMark").val() };
                    $.ajax({
                        url: '../Accounts/Service/MemberService2.asmx/GetGiftByCondition',
                        type: 'POST',
                        data: JSON.stringify(pData),
                        cache: false,
                        contentType: "application/json; charset=utf-8",
                        success: function (pData, textStatus, jqXHR) {
                            var data = eval("(" + pData.d + ")");
                            $("#GridContents").clearGridData(true)
                            $("#GridContents").addRowData('RowNumber', data);
                        },
                        beforeSend: function (jqXHR, settings) {

                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            //  overlay.Hide();
                        },
                        complete: function (XMLHttpRequest, textStatus) {
                            // overlay.Hide();
                        }
                    });
                },
                colNames: [
                    'RowNumber', 'First Name', 'Last Name', 'Email', 'SDT', 'Điểm', 'Quà tặng', 'Ngày Đổi Điểm', 'Ngày nhận', '', 'GiftID', 'ID', 'Trạng Thái'
                ],
                colModel: [
                    { name: 'RowNumber', index: 'ID', width: 50, hidden: true, frozen: true, key: true },
                    { name: 'FirstName', index: 'FirstName', width: 100, frozen: true },
                    { name: 'LastName', index: 'LastName', width: 100, frozen: true },
                    { name: 'Email', index: 'Email', width: 290, align: 'center', editable: true },
                      { name: 'Mobile', index: 'Mobile', width: 70, align: 'center', hidden: true },
                    { name: 'Mark', index: 'Mark', width: 35, align: 'center' },
                    { name: 'GiftName', index: 'Status', width: 160, align: 'center' },

                        {
                            name: 'ConvertFromMarkDateTime', index: 'DateOfBirth', width: 100, align: 'center', formatter: 'date', formatoptions: {
                                srcformat: "m/d/Y",
                                newformat: "d/m/Y"
                            }
                        },
                          {
                              name: 'ReceiptDateTime', index: 'DateOfBirth', width: 100, align: 'center', formatter: 'date'
                           , formatoptions: {
                               srcformat: "m/d/Y",
                               newformat: "d/m/Y"
                           }

                          },
                    { name: 'GiftReceived', index: 'Status', width: 1, align: 'center', hidden: true },
                      { name: 'GiftID', index: 'GiftID', width: 1, align: 'center', hidden: true },
                      { name: 'MemberGiftID', index: 'MemberGiftID', width: 1, align: 'center', hidden: true }
                 , { name: 'Action', index: 'Action', width: 100, align: 'center' }
                ],
                afterEditCell: function (rowid, cellname, val, iRow, iCol) {


                },
                onCellSelect: function (rowid, iCol, cellcontent, e) {
                },
                onSelectRow: function (rowid, status, e) {
                },
                ondblClickRow: function (rowid, iRow, iCol, e) {
                },
                afterInsertRow: function (rowid, rowdata, rowelem) {
                    var actionHtml = $.string.Format('<img src="{1}" class="imgAction"  rowID="{0}" id="Action{0}" loaded="0"/>', rowid, "../../Images/16x16/s_enable.png", "");
                    // console.log(rowdata, rowdata.GiftReceived);
                    if (rowdata.GiftReceived == '0')
                        actionHtml = $.string.Format('<img src="{2}"  class="imgAction"  rowID="{0}" id="ActionGiftFast{0}" loaded="0"/><img src="{1}"  class="imgAction" style="margin-left:5px;" rowID="{0}" id="ActionGift{0}" loaded="0"/>', rowid, "../../Images/16x16/notActive.png", "../../Images/16x16/gift_16x16.png");
                    $("#GridContents").setCell(rowid, 'Action', actionHtml);
                    $("#ActionGift" + rowid).bind('click', function () {
                        Axis.Admin.MemberGift.DialogEdit.Init("UPDATE", rowdata);
                    });
                    $("#ActionGiftFast" + rowid).bind('click', function () {
                        Axis.Admin.MemberGift.Update("UPDATEFAST", rowdata);
                    });

                    if (rowdata.ReceiptDateTime.toString().indexOf('01/01/0001') == 0) {
                        $(thisObj.ID).jqGrid('setCell', rowid, 'ReceiptDateTime', "---");
                    }
                    if (rowdata.ConvertFromMarkDateTime.toString().indexOf('01/01/0001') == 0) {
                        $(thisObj.ID).jqGrid('setCell', rowid, 'ConvertFromMarkDateTime', "---");
                    }
                },
                gridComplete: function () {
                    $('.imgMemberAvatar').tooltip({
                        delay: 0,
                        track: true,
                        showURL: false,
                        bodyHandler: function () {
                            return $("<img/>").attr("src", this.src);
                        }
                    });
                },
                height: 'auto',
                rownumbers: true,
                autowidth: true,
                shrinkToFit: false,
                rowNum: 10,
                pager: thisObj.PagesID
            };
            thisObj.Instance = new CGrid(options);
            thisObj.Instance.Init(thisObj.ID);
            thisObj.Instance.NavGrid();
            thisObj.Instance.FrozenColumns();
        },
        Reload: function () {
            var thisObj = this;
            if (thisObj.Instance)
                thisObj.Instance.ReloadGrid();
        },
        SelectRow: function () {
            var thisObj = this;
            if (thisObj.Instance) {
                return thisObj.Instance.SelectRow();
            }
            return null;
        }
    },
    DialogEdit: {
        ID: "#FormEdit",
        Dialog: null,
        Init: function (action, opts) {
            var thisObj = this;
            Axis.Admin.MemberGift.ClearForm();

            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Edit User",
                    width: 440,
                    height: 400
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
            var buttonText = "";
            switch (action) {
                case "UPDATE":
                    thisObj.Dialog.SetTitle("Edit: " + opts.LoginName);

                    if (opts) {
                        if (opts.ReceiptDateTime.toString().indexOf('01/01/0001') == 0)
                            opts.ReceiptDateTime = $.CFormat.FormatDate(new Date, "dd/MM/yyyy", "en-US", "vi-VN");
                        $.each(opts, function (key, value) {
                            $(thisObj.ID).find("[data-field=" + key + "]").val(value);
                        });
                        $("#cbkIsReceipt").removeAttr("checked");
                        if (opts.IsReceipt == "true") {
                            $("#cbkIsReceipt").attr("checked", "checked");
                        }
                        //  if()
                        $("#txtReceiptQuantity").val(1);
                        buttonText = "Update";
                        thisObj.SetTitle("Cập nhật thông tin");
                    }
                    break;

            }
            var buttons = [
                        {
                            text: buttonText,
                            click: function (e) {
                                Axis.Admin.MemberGift.Update(action, opts);

                            }
                        },
                        {
                            text: "Cancel",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

            ];
            $(thisObj.ID).dialog('option', 'buttons', buttons);
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        },
        SetTitle: function (title) {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.SetTitle(title);
            }
        }
    },
    DialogFilter: {
        ID: "#FormFilter",
        Dialog: null,
        Init: function (type, opts) {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Filter",
                    width: 330,
                    height: 400,
                    buttons: [
                        {
                            text: "Search",
                            click: function (e) {
                                Axis.Admin.MemberGift.Grid.Reload();
                                thisObj.Close();
                            }
                        },
                        {
                            text: "Cancel",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

                    ]
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        }
    },
    ClearForm: function () {

    },

    Event: function () {
        var thisObj = this;
        $("#imgUserAdd").click(function () {
            thisObj.DialogAddGift.Init("INSERT");
        });
        $("#imgUserEdit").click(function () {
            var rowData = thisObj.Grid.SelectRow();
            if (rowData && rowData.ID)
                thisObj.DialogEdit.Init("UPDATE", rowData);
            else {
                $.CAlert.Alert({
                    Title: "Cập nhật trạng thái",
                    Content: "Vui lòng chọn tài khoản cần sửa."
                });
            }
        });
        $("#imgUserDel").click(function () {
            var rowData = thisObj.Grid.SelectRow();
            if (rowData && rowData.ID) {
                $.CAlert.Confirm({
                    Title: "Xóa tài khoản",
                    Content: $.string.Format("Bạn có chắc muốn xóa tài khoản [{0}].", rowData.Email)
                }, function (isOK) {
                    if (isOK)
                        thisObj.Update("DELETE", rowData);
                });
            }
            else {
                $.CAlert.Alert({
                    Title: "Xóa tài khoản",
                    Content: "Vui lòng chọn tài khoản cần xóa."
                });
            }

        });
        $("#imgUserFilter").click(function () {
            thisObj.DialogFilter.Init();
        });

    },
    Update: function (type, opts) {
        var thisObj = this;
        var data = {};
        switch (type) {
            case "INSERT":
                $("#FormEdit").find("input,select").each(function () {
                    var $this = $(this);
                    if ($this.attr("data-field")) {
                        var key = $this.attr("data-field");
                        data[key] = $this.val();
                        if ($this.attr("role") == "datepicker") {
                            data[key] = $.CFormat.FormatDate(value, "yyyy/MM/dd HH:mm", "vi-VN", "en-US");
                        }

                    }
                });
                break;
            case "UPDATE":
                $("#FormEdit").find("input,select").each(function () {
                    var $this = $(this);
                    if ($this.attr("data-field") && $this.attr("data-role") != "INSERT" && $this.attr("no-data") != "1") {
                        var key = $this.attr("data-field");
                        data[key] = $this.val();
                        console.log(key, $this.val());
                    }
                });
                data.IsReceipt = $("#cbkIsReceipt").is(":checked") ? 1 : 0;
                data.ReceiptNote = $("#txtReceiptNote").val();
                data.ActionMemberID = data.ID;

                break;

            case "UPDATEFAST":

                type = "UPDATE";
                data.ActionMemberID = opts.ID;
                data.CategoryID = null;
                data.ID = opts.MemberGiftID;
                data.IsReceipt = 0;
                data.MemberGiftID = opts.MemberGiftID;
                data.ReceiptDateTime = $.CFormat.FormatDate(new Date());
                data.ReceiptNote = "";
                data.ReceiptQuantity = "1";
                data.RowNumber = opts.RowNumber;
                break;

            case "DELETE":
                data.ID = opts.ID;
                break;
        }
        data.Action = type;
        $.ajax({
            url: '../Accounts/Service/MemberService2.asmx/UpdateGiftData',
            type: 'POST',
            data: JSON.stringify(data),
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (pData, textStatus, jqXHR) {
                var data = eval("(" + pData.d + ")");
                if (data.IsSuccessfull) {
                    thisObj.Grid.Reload();
                    thisObj.DialogEdit.Close();
                }

                $.CAlert.Alert({
                    Title: "Thông báo",
                    Content: data.Description
                });

                // $("#GridContents").addRowData('RowNumber', data);
            },
            beforeSend: function (jqXHR, settings) {

            },
            error: function (jqXHR, textStatus, errorThrown) {
                //  overlay.Hide();
            },
            complete: function (XMLHttpRequest, textStatus) {
                // overlay.Hide();
            }
        });
    },
    Validate: function () {

    },
    GetAdminCategory: function () {
        var data = {
            Action: "GetAdminCategory",
            FunctionCode: "AdminCategory",
            Context: "GroupUser"
        };
        $.Ajax({
            url: 'Service/UserService.ashx',
            type: 'POST',
            data: data,
            success: function (data, textStatus, jqXHR) {
                if (data) {
                    data = eval("(" + data + ")");
                    var ret_parent = "";
                    $.each(data, function (index, item) {
                        if (item.ParentID == 0)
                            ret_parent += $.string.Format('<li menuid="{0}"><input type="checkbox" value="{0}" code="{1}" id="menu_{0}" /><label for="menu_{0}">{2}</label></li>', item.ID, item.Code, $.RemoveHTMLTags(item.Name));
                    });

                    $(".Menu_Tree_Items").html(ret_parent);
                    $.each(data, function (index, item) {
                        var ret_child = "";
                        if (item.ParentID != 0) {
                            ret_child += $.string.Format('<li menuid="{0}"><input type="checkbox" value="{0}" code="{1}" id="submenu_{0}" /><label for="submenu_{0}">{2}</label></li>', item.ID, item.Code, $.RemoveHTMLTags(item.Name));
                            var $parent = $(".Menu_Tree_Items li[menuid='" + item.ParentID + "']");
                            if ($parent.length) {
                                if ($parent.find("ul").length == 0) {
                                    $parent.append("<ul></ul>");
                                }
                                $(".Menu_Tree_Items li[menuid='" + item.ParentID + "'] ul").append(ret_child);
                            }
                        }

                    });
                    $('.Menu_Tree').tree();
                }
            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },
    DialogAddGift: {
        ID: "#AddGift",
        Dialog: null,
        Init: function (action, opts) {
            var thisObj = this;
            Axis.Admin.MemberGift.ClearForm();

            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Edit User",
                    width: 440,
                    height: 400
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
            var buttonText = "";
            switch (action) {
                case "INSERT":
                    thisObj.Dialog.SetTitle("Thêm quà tặng");
                    $(thisObj.ID).find("[data-role='INSERT']").show();

                    buttonText = "Add";

                    break;

            }
            var buttons = [
                        {
                            text: buttonText,
                            click: function (e) {
                                Axis.Admin.MemberGift.AddGiftLottory(action, opts);

                            }
                        },
                        {
                            text: "Cancel",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

            ];
            $(thisObj.ID).dialog('option', 'buttons', buttons);
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        },
        SetTitle: function (title) {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.SetTitle(title);
            }
        }
    }
};
$(function () {
    Axis.Admin.MemberGift.Init();

});
function ShowEdit(rowID) {
    var thisObj = Axis.Admin.MemberGift;
    var rowData = $(thisObj.Grid.ID).jqGrid('getRowData', rowID);
    if (rowData && rowData.MemberGiftID)
        thisObj.DialogEdit.Init("UPDATE", rowData);
}

function ShowDelete(rowID) {
    var thisObj = Axis.Admin.MemberGift;
    if (rowID) {
        var rowData = $(thisObj.Grid.ID).jqGrid('getRowData', rowID);
        $.CAlert.Confirm({
            Title: "Xóa tài khoản",
            Content: $.string.Format("Bạn có chắc muốn xóa tài khoản: [{0}].", rowData.LoginName)
        }, function (isOK) {
            if (isOK)
                thisObj.Update("DELETE", { ID: rowID });
        });
    }
    else {
        $.CAlert.Alert({
            Title: "Xóa bài viết",
            Content: "Vui lòng chọn bài viết cần xóa."
        });
    }

}


function ExportExcel(ID) {
    //{ ProjectID=$("#ddlProjectList").val()& GiftID= $("#ddlGift").val()& GiftReveiced= $("#ddlStatus").val()& FromDate= $("#txtFromDate").val()& ToDate= $("#txtToDate").val()& FromMark= $("#txtFromMark").val()& ToMark= $("#txtToMark").val() };
    var urlParam = $.string.Format("ProjectID={0}&GiftID={1}&GiftReveiced={2}&FromDate={3}&ToDate={4}&FromMark={5}&ToMark={6}", $("#ddlProjectList").val(), $("#ddlGift").val(), $("#ddlStatus").val(), $("#txtFromDate").val(), $("#txtToDate").val(), $("#txtFromMark").val(), $("#txtToMark").val());
    window.open('ExportExcel.aspx?' + urlParam);
}